from typing import List, Dict

import requests
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI(title="聊天历史管理API", version="1.0.0")

# API配置
API_URL = "https://api.siliconflow.cn/v1/chat/completions"
API_KEY = "sk-rnqurwrjarpxjetwkcphjymkcrbxpoyhpueaxwtkevmdwhlw"

# 模拟数据库存储用户聊天历史
user_chat_history: Dict[str, List[Dict[str, str]]] = {}


class ChatRequest(BaseModel):
    user_id: str
    message: str


class ChatResponse(BaseModel):
    user_id: str
    response: str
    chat_history: List[Dict[str, str]]


def get_ai_response(messages: List[Dict[str, str]]) -> str:
    """调用AI模型获取回复"""
    payload = {
        "model": "Qwen/QwQ-32B",
        "messages": messages
    }
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        response.raise_for_status()
        return response.json()['choices'][0]['message']['content']
    except requests.exceptions.RequestException as e:
        raise HTTPException(status_code=500, detail=f"AI模型调用失败: {str(e)}")


@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(chat_request: ChatRequest):
    """处理用户聊天请求"""
    user_id = chat_request.user_id
    user_message = chat_request.message

    # 获取用户历史记录（如果没有则创建）
    if user_id not in user_chat_history:
        user_chat_history[user_id] = []

    # 添加用户消息到历史记录
    user_chat_history[user_id].append({
        "role": "user",
        "content": user_message
    })

    # 获取AI回复
    ai_response = get_ai_response(user_chat_history[user_id])

    # 添加AI回复到历史记录
    user_chat_history[user_id].append({
        "role": "assistant",
        "content": ai_response
    })

    return ChatResponse(
        user_id=user_id,
        response=ai_response,
        chat_history=user_chat_history[user_id]
    )


@app.get("/history/{user_id}", response_model=List[Dict[str, str]])
async def get_chat_history(user_id: str):
    """获取用户聊天历史"""
    if user_id not in user_chat_history:
        return []
    return user_chat_history[user_id]


@app.delete("/history/{user_id}")
async def clear_chat_history(user_id: str):
    """清除用户聊天历史"""
    if user_id in user_chat_history:
        user_chat_history[user_id] = []
        return {"message": f"用户 {user_id} 的聊天历史已清除"}
    return {"message": f"用户 {user_id} 没有聊天历史"}


@app.get("/")
async def root():
    return {"message": "聊天历史管理API正在运行", "docs": "/docs"}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
